import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:frontend/models/global.dart';
import 'package:frontend/pages/publishItemPage.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:frontend/states/NetState.dart';
import 'package:provider/provider.dart';

import '../models/store.dart';
import '../widgets/expandableFab.dart';
import 'ItemPage.dart';

class StorePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return StorePageState();
  }
}

class StorePageState extends State<StorePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text('我的店铺'),
      ),
      body: Consumer<NetState>(builder: (context, netState, widget) {
        return FutureBuilder<Store?>(
          future: fetchStore(Global.profile.user!.id),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                //return Text(snapshot.error.toString());
                return const Icon(Icons.error);
              } else {
                if (snapshot.data == null) {
                  return Center(
                    child: Column(
                      children: [
                        Text('您还没有开设店铺'),
                        ElevatedButton(
                            onPressed: () {
                              openStore(Global.profile.user!.id,
                                  "${Global.profile.user!.name}的店");
                            },
                            child: Text('开设店铺'))
                      ],
                    ),
                  );
                } else {
                  Global.profile.store = snapshot.data;
                  return GridView.count(
                      restorationId: 'grid_view_demo_grid_offset',
                      crossAxisCount: 4,
                      mainAxisSpacing: 8,
                      crossAxisSpacing: 8,
                      padding: const EdgeInsets.all(8),
                      childAspectRatio: 1,
                      children: snapshot.data!.items
                          .map((e) => ItemCard(
                                itemId: e.id,
                                image: Image.memory(e.img),
                                title: e.name,
                                price: e.price,
                                buyer: e.buyer,
                                buyer_id: e.buyer_id,
                                //itemId: e.id,
                              ))
                          .toList());
                }
              }
            } else {
              // 请求未结束，显示loading
              return CircularProgressIndicator();
            }
          },
        );
      }),
      floatingActionButton: ExpandableFab(
        distance: 112.0,
        children: [
          /*ActionButton(
            onPressed: () => _showAction(context, 0),
            icon: const Icon(Icons.format_size),
          ),
          ActionButton(
            onPressed: () => _showAction(context, 1),
            icon: const Icon(Icons.insert_photo),
          ),
          ActionButton(
            onPressed: () => _showAction(context, 2),
            icon: const Icon(Icons.videocam),
          ),*/

          ActionButton(
            icon: Icon(Icons.publish),
            onPressed: () => {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => PublishItemPage()))
            },
          ),
          ActionButton(
            icon: Icon(Icons.refresh),
            onPressed: () => setState(() {}),
          ),
          ActionButton(icon: Icon(Icons.check_box_outline_blank))
        ],
      ),
      /*floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
      floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,*/

      /*bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          child: Row(
            children: [],
          )),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => PublishItemPage()));
        },
        tooltip: '发布商品',
        child: Icon(Icons.add),
      ),*/
    );
  }

  void _showAction(BuildContext context, int index) {
    showDialog<void>(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Text("xs"),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('CLOSE'),
            ),
          ],
        );
      },
    );
  }
}

class ItemCard extends StatefulWidget {
  final int itemId;
  final Image image;
  final String title;
  final int price;
  final String? buyer;
  final int buyer_id;

  const ItemCard(
      {super.key,
      required this.itemId,
      required this.image,
      required this.title,
      required this.price,
        this.buyer,
      required this.buyer_id});

  @override
  State<ItemCard> createState() => _ItemCardState();
}

class _ItemCardState extends State<ItemCard> {
  @override
  Widget build(BuildContext context) {
    return GridTile(
      footer: Material(
        color: Colors.transparent,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(4)),
        ),
        clipBehavior: Clip.antiAlias,
        child: GridTileBar(
          backgroundColor: Colors.black45,
          title: Text('${widget.title} ￥${widget.price} ${widget.buyer ?? ''}'),
          subtitle: Row(
            children: [
              TextButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                ItemPage(itemId: widget.itemId,canBuy: false,)));
                  },
                  child: Text('详情')),
              TextButton(
                  onPressed: () async {
                    var res = await _showModalBottomSheet();
                    if (res != null) {
                      delItemInStore(widget.itemId);
                      Provider.of<NetState>(context, listen: false)
                          .somethingChangedInBackend();
                    }
                  },
                  child: Text('下架')),
            ],
          ),
        ),
      ),
      child: Stack(
        alignment: Alignment.center,
        fit: StackFit.expand,
        children: [
          widget.image,
          if (widget.buyer_id > 0)
            Container(
              color: Color(0x1A7A7171),
              transform: Matrix4.rotationZ(.4), //卡片倾斜变换
              alignment: Alignment.center, //卡片内文字居中
              child: Text(
                //卡片文字
                "sold out",
                style: TextStyle(color: Colors.redAccent, fontSize: 40.0),
              ),
            ),
        ],
      ),
    );
  }

  Future<bool?> _showModalBottomSheet() {
    return showModalBottomSheet<bool>(
      context: context,
      builder: (BuildContext context) {
        return ListView(
          children: [
            Text("确认下架商品？",
                style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.w600,
                    fontSize: 45)),
            ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("下架商品"))
          ],
        );
      },
    );
  }
}
